package com.bnlr.lrparking.appui.stall;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.like.LikeButton;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.util.BDMapUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.search.SearchActivity;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.CarPlaceData;
import com.bnlr.lrparking.model.CarPlaceDetailM;
import com.bnlr.lrparking.model.CarPlaceM;
import com.bnlr.lrparking.model.CollectParkBean;
import com.bnlr.lrparking.model.Location;
import com.bnlr.lrparking.widget.NativeDialog;
import com.bnlr.lrparking.reserve.ExampleUtil;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hp on 2017/8/14.
 */

public class PrakFragment extends BaseFragment implements SensorEventListener ,View.OnClickListener{

    private RelativeLayout laySearch;
    private TextureMapView bmapView;
    private ImageView ivMyLocation;
    private Button zoomin,zoomout;
    private TextView tvCarplaceName;
    private TextView tvMianfei;
    private TextView tvJiamengzhong;
    private TextView tvCarJuli;
    private TextView tvCarKong;
    private TextView tvCarTime;
    private TextView tvCarXiaohao;
    private TextView tvPhone;
    private TextView tvAddress;
    private TextView tv_collect;
    private LikeButton likeButton;
    private LinearLayout layCarplaceInfo;
    private LinearLayout bottom_other;
    private LinearLayout lay_daohang,lay_callphone;
    private RelativeLayout lay_collect;
    /**
     * 地图相关
     */
    private LatLng mCenterLatLng;
    private LatLng mLatLng;
    private LatLng mOldLatLng;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BaiduMap mBaiduMap;
    private GeoCoder mSearch;
    String address;
    List<CarPlaceData> carplaceList = new ArrayList<>();
    BitmapDescriptor mCurrentMarker;
    private Double lastX = 0.0;
    private BDMapUtils bdMapUtils = new BDMapUtils();
    private RelativeLayout bottom_dialog;
    private LinearLayout raly_all;
    private boolean isBottomOne = false;
    CarPlaceData carplace;
    private int waitReadMessage;
    private View mview;
    private RelativeLayout imgMessage,rely_dw;
    private TextView tvLocationCity;
    private String successLocation;
    private Marker mMarker;
    private CarPlaceData oldCarData;
    private CarCommon carCommon=new CarCommon();
    private CarPlaceData daohangPlace;
    private LinearLayout lay_carplace_info;
    private static final int MAP_RADIUS = 300;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mview = inflater.inflate(R.layout.fragment_prak, container, false);
        initView();
        return mview;
    }



    private void initView(){
        bmapView=(TextureMapView)mview.findViewById(R.id.bmapView);
        imgMessage=(RelativeLayout)mview.findViewById(R.id.rely_message);
        laySearch=(RelativeLayout)mview.findViewById(R.id.lay_search);
        ivMyLocation=(ImageView)mview.findViewById(R.id.iv_my_location);
        tvMianfei=(TextView)mview.findViewById(R.id.tv_mianfei);
        tvCarJuli=(TextView)mview.findViewById(R.id.tv_car_juli);
        tvJiamengzhong=(TextView)mview.findViewById(R.id.tv_jiamengzhong);
        tvCarKong=(TextView)mview.findViewById(R.id.tv_car_kong);
        tvCarTime=(TextView)mview.findViewById(R.id.tv_car_time);
        tvCarXiaohao=(TextView)mview.findViewById(R.id.tv_car_xiaohao);
        tvPhone=(TextView)mview.findViewById(R.id.tv_phone);
        tvAddress=(TextView)mview.findViewById(R.id.tv_address);
        tv_collect=(TextView)mview.findViewById(R.id.tv_collect);
        likeButton=(LikeButton)mview.findViewById(R.id.likeButton);
        layCarplaceInfo=(LinearLayout) mview.findViewById(R.id.lay_carplace_info);
        bottom_other=(LinearLayout) mview.findViewById(R.id.bottom_other);
        zoomin=(Button)mview.findViewById(R.id.zoomin);
        zoomout=(Button)mview.findViewById(R.id.zoomout);
        lay_daohang=(LinearLayout)mview.findViewById(R.id.lay_daohang);
        lay_callphone=(LinearLayout)mview.findViewById(R.id.lay_callphone);
        lay_collect=(RelativeLayout) mview.findViewById(R.id.lay_collect);
        tvCarplaceName=(TextView)mview.findViewById(R.id.tv_carplace_name);
        bottom_dialog = (RelativeLayout)mview.findViewById(R.id.bottom_dialog);
        rely_dw = (RelativeLayout) mview.findViewById(R.id.rely_dw);
        raly_all = (LinearLayout)mview.findViewById(R.id.raly_all);
        tvLocationCity = (TextView) mview.findViewById(R.id.tv_city);
        lay_carplace_info=(LinearLayout) mview.findViewById(R.id.lay_carplace_info);
        imgMessage.setOnClickListener(this);
        laySearch.setOnClickListener(this);
        ivMyLocation.setOnClickListener(this);
        zoomin.setOnClickListener(this);
        zoomout.setOnClickListener(this);
        lay_daohang.setOnClickListener(this);
        lay_callphone.setOnClickListener(this);
        lay_collect.setOnClickListener(this);
        bottom_other.setOnClickListener(this);
        rely_dw.setOnClickListener(this);
        // 隐藏百度logo
        bdMapUtils.configMap(bmapView);
        // 不显示地图上比例尺
        bmapView.showScaleControl(false);
        bmapView.showZoomControls(false);
        mBaiduMap = bmapView.getMap();
        mLocClient = new LocationClient(getActivity());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(0);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        requestPermiss();
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.zoomTo(17));
        mCurrentMode = MyLocationConfiguration.LocationMode.FOLLOWING;
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                mCurrentMode, true, mCurrentMarker));
        //展示如何进行地理编码搜索（用地址检索坐标）、反地理编码搜索（用坐标检索地址）
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(new MyGetGeoCoderResultListener());
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             * @param status
             * 地图状态改变开始时的地图状态
             */
            @Override
            public void onMapStatusChangeStart(MapStatus status) {
                Log.i("onMapStatusChangeStart", "onMapStatusChangeStart");

            }
            /**
             * 地图状态改变结束
             * @param status
             * 地图状态改变结束后的地图状态
             */
            @Override
            public void onMapStatusChangeFinish(MapStatus status) {

                mOldLatLng = status.target;
                Log.e("手势操作完成", "----------");
                /*OverlayOptions circleOption = new CircleOptions().center(new LatLng(status.target.latitude,status.target.longitude))
                        .radius(200).fillColor(0x3A007aff);

                // 在地图上添加Marker，并显示
                mBaiduMap.addOverlay(circleOption);*/
                /**
                 *  获取中心经纬度
                 *  */
                if (DistanceUtil.getDistance(mOldLatLng, mCenterLatLng) > MAP_RADIUS) {
                    mCenterLatLng = status.target;
                    mCentertLat = mCenterLatLng.latitude;
                    mCenterLon = mCenterLatLng.longitude;
                    Log.e("经纬度",mCentertLat+"-"+mCenterLon);
                    //getData();
                    mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(mCenterLatLng));
                    AppConfig.getInstance().putString("Lat", mCenterLatLng.latitude+"");//用户名
                    AppConfig.getInstance().putString("Lon", mCenterLatLng.longitude+"");//昵称
                }
            }

            /**
             * 地图状态变化中
             * @param status
             *            当前地图状态
             */
            @Override
            public void onMapStatusChange(MapStatus status) {
                Log.i("onMapStatusChange", "onMapStatusChange");

            }
        });
        //调用BaiduMap对象的setOnMarkerDragListener方法设置marker的监听
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                for (int i = 0; i < carplaceList.size(); i++) {
                    //判断经纬度
                    if (marker.getPosition().latitude == Double.valueOf(carplaceList.get(i).getLat()) && marker.getPosition().longitude == Double.valueOf(carplaceList.get(i).getLng())) {
                        /**
                         * 点击位置图标跳转(这里可以修改成底部弹框)
                         */
//                        Intent intent=new Intent(getActivity(), CarPlaceDetailActivity.class);
//                        intent.putExtra("lat", mCentertLat);
//                        intent.putExtra("lon", mCenterLon);
//                        intent.putExtra("CarPlace",carplaceList.get(i));
//                        startActivity(intent);

                        if (mMarker != null && mMarker != marker && oldCarData != null) {
                            setPointImg(mMarker,oldCarData,true);
                        }
                        setPointImg(marker,carplaceList.get(i),false);
                        daohangPlace = carplaceList.get(i);
                        getCarData(carplaceList.get(i).getId());
                        if (isBottomOne == false) {
                            Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.bottom_in);
                            raly_all.setAnimation(animation);
                            bottom_dialog.setVisibility(View.VISIBLE);
                            isBottomOne = true;
                            if (carplaceList.get(i).getIsjoin().equals("0")){
                                lay_carplace_info.setVisibility(View.VISIBLE);
                            }else {
                                lay_carplace_info.setVisibility(View.GONE);
                            }
                        }
                        break;

                    }
                }

                return false;
            }
        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                bottom_dialog.setVisibility(View.GONE);
                isBottomOne = false;

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
    }

    /**
     * 请求权限
     */
    private void requestPermiss() {
        if ((ContextCompat.checkSelfPermission(getActivity(), "android.permission.ACCESS_COARSE_LOCATION")) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 66);
        } else {
            mLocClient.start();
        }
    }


    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }


    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
//            mCurrentDirection = (int) x;
//            locData = new MyLocationData.Builder()
//                    .accuracy(mCurrentAccracy)
//                    // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(mCurrentDirection).latitude(mCurrentLat)
//                    .longitude(mCurrentLon).build();
//            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }
    /**
     * 获取当前位置范围内的车位信息
     */
    @Override
    public void getData() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetParkByLocation");
            mRequest.add("m", "200");
            mRequest.add("phonePara",Application.DEVICE_ID);
            mRequest.add("lng", mCenterLon);
            mRequest.add("lat", mCentertLat);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));

            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<CarPlaceM>(getActivity(), true, CarPlaceM.class) {
                        @Override
                        public void doWork(CarPlaceM data, String code) {
                            if ("1".equals(code)) {
                                carplaceList.clear();
                                carplaceList.addAll(data.getData());
                                mBaiduMap.clear(); // 重置mBaiduMap
                                OverlayOptions circleOption = new CircleOptions().center(new LatLng(mCenterLatLng.latitude,mCenterLatLng.longitude))
                                        .radius(MAP_RADIUS).fillColor(0x2800caa3);

                                // 在地图上添加Marker，并显示
                                mBaiduMap.addOverlay(circleOption);
                                for (int i = 0; i < carplaceList.size(); i++) {
                                    carplace = carplaceList.get(i);
                                    if ("0".equals(carplace.getIsjoin())) {
                                        if (Integer.valueOf(carplace.getChewei()) > 10) {
                                            view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
                                            marker_name = (TextView) view.findViewById(R.id.marker_name);
                                            marker_img = (ImageView) view.findViewById(R.id.marker_img);
                                            if(Integer.valueOf(carplace.getChewei()) > 99){
                                                marker_name.setTextSize(12);
                                                marker_name.setText("99+");
                                            } else {
                                                marker_name.setText(carplace.getChewei());
                                            }
                                            marker_name.setTextColor(getResources().getColor(R.color.main_color));
                                            marker_img.setImageResource(R.mipmap.index_position01);
                                            mBaiduMap.addOverlay(new MarkerOptions().position(new LatLng(Double.valueOf(carplace.getLat()), Double.valueOf(carplace.getLng())))
                                                    .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view))));
                                        } else {
                                            view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
                                            marker_name = (TextView) view.findViewById(R.id.marker_name);
                                            marker_img = (ImageView) view.findViewById(R.id.marker_img);
                                            marker_name.setText(carplace.getChewei());
                                            marker_img.setImageResource(R.mipmap.index_position02);
                                            marker_name.setTextColor(getResources().getColor(R.color.red_color));
                                            mBaiduMap.addOverlay(new MarkerOptions().position(new LatLng(Double.valueOf(carplace.getLat()), Double.valueOf(carplace.getLng())))
                                                    .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view))));

                                        }
                                    } else if ("1".equals(carplace.getIsjoin())) {
                                        view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
                                        marker_name = (TextView) view.findViewById(R.id.marker_name);
                                        marker_img = (ImageView) view.findViewById(R.id.marker_img);
                                        marker_img.setImageResource(R.mipmap.index_position03);
                                        mBaiduMap.addOverlay(new MarkerOptions().position(new LatLng(Double.valueOf(carplace.getLat()), Double.valueOf(carplace.getLng())))
                                                .icon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view))));
                                    }
                                }
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!TextUtils.equals("1", code)) {
                                    carplaceList.clear();
                                    mBaiduMap.clear();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    float zoomLevel;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bottom_other:
                break;
            case R.id.lay_collect:
                break;
            case R.id.lay_search://搜索车位
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("lat", mCentertLat);
                intent.putExtra("lon", mCenterLon);
                startActivity(intent);
                break;
            case R.id.iv_my_location://定位点移至中心
                LatLng ll = new LatLng(Params.CurrentLat, Params.CurrentLon);
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll); //定位点移至中心
                mBaiduMap.animateMapStatus(u);
                break;
            case R.id.zoomin://加大地图
                zoomLevel = mBaiduMap.getMapStatus().zoom;
                if (zoomLevel <= 19) {
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
                    zoomout.setEnabled(true);
                } else {
                    CommonUtil.showToask(getActivity(), "已经放至最大！");
                    zoomin.setEnabled(false);
                }
                break;
            case R.id.zoomout://缩小地图
                zoomLevel = mBaiduMap.getMapStatus().zoom;
                if (zoomLevel > 4) {
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
                    zoomin.setEnabled(true);
                } else {
                    zoomout.setEnabled(false);
                    CommonUtil.showToask(getActivity(), "已经缩至最小！");
                }
                break;
            case R.id.lay_daohang:
                /**
                 * 检测地图工具
                 */
                Location loc_now = new Location(Params.CurrentLat, Params.CurrentLon, "起始点");
                Location loc_end = new Location(Double.valueOf(daohangPlace.getLat()), Double.valueOf(daohangPlace.getLng()), "终点");
                NativeDialog msgDialog = new NativeDialog(getActivity(), loc_now, loc_end);
                msgDialog.show();
                break;
            //拨打电话
            case R.id.lay_callphone:
                carCommon.phoneDialog(getActivity());
                break;

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1111 && resultCode == 2222) {
            String selectCity = data.getStringExtra("picked_city");
            tvLocationCity.setText(selectCity);
            AppConfig.getInstance().putString("strCity",selectCity);
            mSearch.geocode(new GeoCodeOption()
                    .city("").address(selectCity));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 66){
            if (grantResults != null) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocClient.start();
                    mLocClient.requestLocation();
                } else {
                    ToastUtils.showShort("用户已拒绝定位权限，请在设置中赋予权限");
                }
            }
        }
    }

    /**
     * 定位SDK监听函数
     */
    private int mCurrentDirection = 0;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private double mCentertLat = 0.0;
    private double mCenterLon = 0.0;
    private float mCurrentAccracy;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || bmapView == null) {
                AppConfig.getInstance().putString("strCity","郑州市");
                mLocClient.start();
                return;
            }
            mCurrentAccracy = location.getRadius();
            Params.CurrentLat = location.getLatitude();//获取纬度信息
            Params.CurrentLon = location.getLongitude(); //获取经度信息

            if (isFirstLoc) {
                successLocation = location.getCity();
                tvLocationCity.setText(location.getCity());
                AppConfig.getInstance().putString("strCity",location.getCity());
                mCentertLat = location.getLatitude();
                mCenterLon = location.getLongitude();
                mCurrentLat = location.getLatitude();
                mCurrentLon = location.getLongitude();
                isFirstLoc = false;
                LatLng ll = new LatLng(Params.CurrentLat, Params.CurrentLon);
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll); //定位点移至中心
                mBaiduMap.animateMapStatus(u);
                mCenterLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                getData();
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
            Params.CurrentLat = poiLocation.getLatitude();
        }
    }

    /**
     * 地理编码监听器
     */
    View view;
    TextView marker_name;
    ImageView marker_img;

    public class MyGetGeoCoderResultListener implements OnGetGeoCoderResultListener {
        @Override
        public void onGetGeoCodeResult(GeoCodeResult result) {  //地址转坐标
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                CommonUtil.showToask(getActivity(), "抱歉，未能找到结果");
                return;
            }
            mCentertLat = result.getLocation().latitude;
            mCenterLon = result.getLocation().longitude;
            LatLng ll = new LatLng(mCentertLat, mCenterLon);
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll); //定位点移至中心
            mBaiduMap.animateMapStatus(u);
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) { //反Geo搜索，坐标转地址
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                CommonUtil.showToask(getActivity(), "抱歉，未能找到结果");
                return;
            }
            address = result.getAddress();
            mCentertLat = result.getLocation().latitude;
            mCenterLon = result.getLocation().longitude;
            getData();
        }
    }

    private Bitmap getViewBitmap(View addViewContent) {
        addViewContent.setDrawingCacheEnabled(true);
        addViewContent.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0,
                addViewContent.getMeasuredWidth(),
                addViewContent.getMeasuredHeight());
        addViewContent.buildDrawingCache();

        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    @Override
    public void onStop() {
        //取消注册传感器监听
        super.onStop();
        if (bmapView != null) {
            bmapView.onPause();

        }
        if (mLocClient != null) {
            mLocClient.stop();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (bmapView != null) {
            bmapView.onResume();
        }
        isForeground = true;
    }

    /**
     * 极光推送
     */
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static boolean isForeground = false;

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, filter);
    }

    public static class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isForeground = false;
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (bmapView != null) {
            bmapView.onPause();
        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //退出时销毁定位
        if (mLocClient != null) {
            mLocClient.stop();
        }
        //关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理

        if (bmapView != null) {
            bmapView.onDestroy();
        }
        bmapView = null;
        mSearch.destroy();
    }

    //这个是点击标注车场数据的请求
    CarPlaceDetailM.DataBean placeDetail;

    private void getCarData(String id) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetParkingById");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("id", id);
            mRequest.add("phonePara",Application.DEVICE_ID);
            mRequest.add("lng", mCenterLon);
            mRequest.add("lat", mCentertLat);
            // 添加到请求队列
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<CarPlaceDetailM>(getActivity(), true, CarPlaceDetailM.class) {
                        @Override
                        public void doWork(CarPlaceDetailM data, String code) {
                            if ("1".equals(code)) {
                                placeDetail = data.getData();
                                initCarPlaceDetail();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                } else {
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }

    private void initCarPlaceDetail() {
        tvCarplaceName.setText(placeDetail.getName());
        if ("0".equals(placeDetail.getIsjoin())) {
            tvMianfei.setVisibility(View.VISIBLE);
            tvJiamengzhong.setVisibility(View.GONE);
            tvCarTime.setVisibility(View.VISIBLE);
            tvCarTime.setText("开放时间：" + placeDetail.getOpentime());
            layCarplaceInfo.setVisibility(View.VISIBLE);
        } else {
            tvMianfei.setVisibility(View.GONE);
            tvCarTime.setText("开放时间：24小时开放");
            tvJiamengzhong.setVisibility(View.VISIBLE);
        }
        if ("1".equals(placeDetail.getIsFavorite())) {
            likeButton.setLiked(true);
            tv_collect.setTextColor(getResources().getColor(R.color.main_color));
        } else {
            likeButton.setLiked(false);
            tv_collect.setTextColor(getResources().getColor(R.color.black_color));
        }
        tvCarJuli.setText("距离：" + placeDetail.getJuli());
        tvCarKong.setText("空车位：" + placeDetail.getChewei());
        tvCarXiaohao.setText("消耗：" + placeDetail.getSharevalue() + "共享值/小时");
        String phone = placeDetail.getPhone();
        if (TextUtils.isEmpty(phone)) {
            phone = "暂无";
        }
        //tvPhone.setText("电话：" + phone);
        tvAddress.setText("地址：" + placeDetail.getAddress());
        likeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(placeDetail.getIsFavorite())) {
                    //   点击取消
                    collect(true);
                } else {
                    //   点击收藏
                    collect(false);
                }
            }
        });

    }
    public void collect (final boolean isCancel) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "SetFavorite");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("parkId", placeDetail.getId());
            mRequest.add("phonePara",Application.DEVICE_ID);
            LogUtils.e("id" + placeDetail.getId() +"--" +"phonePara" + Application.DEVICE_ID);
            // 添加到请求队列
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<CollectParkBean>(getActivity(), true, CollectParkBean.class) {
                        @Override
                        public void doWork(CollectParkBean data, String code) {
                            if ("1".equals(code)) {
                                if (isCancel == true) {
                                    likeButton.setLiked(false);
                                    tv_collect.setTextColor(getResources().getColor(R.color.black_color));
                                    placeDetail.setIsFavorite("0");
                                } else {
                                    likeButton.setLiked(true);
                                    tv_collect.setTextColor(getResources().getColor(R.color.main_color));
                                    placeDetail.setIsFavorite("1");
                                }
                            } else {
                                LogUtils.e(data.getMsg());
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {

                                } else {
                                    CommonUtil.showToask(getActivity(), obj.getString("msg"));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }
    public void setPointImg (Marker marker ,CarPlaceData carplace,boolean icCancel) {
        if ("0".equals(carplace.getIsjoin())) {
            if (Integer.valueOf(carplace.getChewei()) > 10) {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
                TextView marker_name = (TextView) view.findViewById(R.id.marker_name);
                ImageView marker_img = (ImageView) view.findViewById(R.id.marker_img);
                if(Integer.valueOf(carplace.getChewei()) > 99){
                    marker_name.setTextSize(12);
                    marker_name.setText("99+");
                } else {
                    marker_name.setText(carplace.getChewei());
                }
                marker_name.setTextColor(getResources().getColor(R.color.main_color));
                if (icCancel) {
                    marker_img.setImageResource(R.mipmap.index_position01);
                } else {
                    marker_img.setImageResource(R.mipmap.home_cooper1_nor);
                }
                marker.setIcon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));
            } else {
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
                TextView marker_name = (TextView) view.findViewById(R.id.marker_name);
                ImageView marker_img = (ImageView) view.findViewById(R.id.marker_img);
                marker_name.setText(carplace.getChewei());
                if (icCancel) {
                    marker_img.setImageResource(R.mipmap.index_position02);
                } else {
                    marker_img.setImageResource(R.mipmap.home_cooper2_nor);
                }
                marker_name.setTextColor(getResources().getColor(R.color.red_color));
                marker.setIcon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));
            }
        } else if ("1".equals(carplace.getIsjoin())) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.layout_marker, null);
            ImageView marker_img = (ImageView) view.findViewById(R.id.marker_img);
            if (icCancel) {
                marker_img.setImageResource(R.mipmap.index_position03);
            } else {
                marker_img.setImageResource(R.mipmap.home_noncooper_nor);
            }
            marker.setIcon(BitmapDescriptorFactory.fromBitmap(getViewBitmap(view)));
        }
        oldCarData = carplace;
        mMarker = marker;
    }
}
